package com.wt.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wt.admin.config.SecUtils;
import com.wt.admin.entity.LoginAccount;
import com.wt.admin.entity.Register;
import com.wt.admin.entity.WqunAccount;
import com.wt.admin.entity.WqunBlog;
import com.wt.admin.entity.rewentity.LoginUser;
import com.wt.admin.service.WqunAdminService;
import com.wt.commonutils.R;
import com.wt.redis.RedisCache;
import com.wt.security.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Api(tags = "弱化版登录")
@RestController
@RequestMapping("/testLoginController")
@CrossOrigin
public class TestLoginController {

    @Autowired
    private WqunAdminService wqunAdminService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    RedisTemplate redisTemplate;

//    //邮箱验证码登录
//    @ApiOperation("邮箱验证码登录")
//    @GetMapping("/emailLogin/{email}/{code}")
//    @PreAuthorize("hasAnyAuthority('wqunAccountController:updateMyEmail')")
//    public R emailLogin(@PathVariable("email") String email,@PathVariable("code") String code){
//        String emailCode = (String) redisTemplate.opsForValue().get(email);//获取验证码
//        if(emailCode == null || emailCode.equals("")){
//            return R.error().message("未发送验证码或验证码已过期，请重新发送");
//        }
//        if(!emailCode.equals(code)){
//            return R.error().message("验证码错误，请重新输入");
//        }
//        return R.error();
//    }


    //退出登录
    @ApiOperation("退出登录")
    @GetMapping("loginOut")
    @PreAuthorize("hasAnyAuthority('testLoginController:loginOut')")
    public R loginOut(){
        String id = SecUtils.getUserMess().getId();
        redisCache.deleteObject("login:" + id);
        return R.ok();
    }



    //登录
    @ApiOperation("登录")
    @PostMapping("login")
    public R login(@RequestBody LoginAccount loginAccount){
        //进行认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginAccount.getAccountPhone(),loginAccount.getAccountPass());

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //没有通过，给出相应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        //通过了，使用id生成一个jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String id = loginUser.getWqunAccount().getId().toString();
        //把完整的信息存入redis中 userid最为key
        redisCache.setCacheObject("login:" + id,loginUser);
//        LoginUser loginUser2 = redisCache.getCacheObject("login:" + id);
        //token账号加密
        String jwt = JwtUtil.createJWT(id);
        Map<String,String> map = new HashMap<>();
        return R.ok().message("登录成功").data("token",jwt);
    }

    //注册用户
    @ApiOperation("注册用户")
    @PostMapping("register")
    public R register(@RequestBody WqunAccount wqunAccount){
        //手机号是否符合规格
        if(wqunAccount.getPhone() == null || wqunAccount.getPhone().equals("") ){
            return R.error().message("账号为空");
        }
        if(wqunAccount.getPhone().length() > 11){
            return R.error().message("账号最多为11位");
        }

        if(wqunAccount.getPhone().contains("@")){
            return R.error().message("账号不允许含有'@'字符");
        }

        //昵称是否符合规格
        if(wqunAccount.getNickName() == null || wqunAccount.getNickName().equals("") ){
            return R.error().message("昵称为空");
        }
        if(wqunAccount.getNickName().length() > 8){
            return R.error().message("昵称最多为8位");
        }



       //判断是否存在该账号
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",wqunAccount.getPhone());
        int countByPhone = wqunAdminService.count(queryWrapper);
        if(countByPhone != 0){
            return R.error().message("该账号已经存在");
        }

        //判断是否存在该邮箱
//        queryWrapper = new QueryWrapper();
//        queryWrapper.eq("email",wqunAccount.getEmail());
//        int countByEmail = wqunAdminService.count(queryWrapper);
//        if(countByEmail != 0){
//            return R.error().message("该邮箱已经存在，请登录");
//        }

        queryWrapper = new QueryWrapper();
        queryWrapper.eq("nick_name",wqunAccount.getNickName());
        int countByName = wqunAdminService.count(queryWrapper);
        if(countByName != 0){
            return R.error().message("该昵称已经存在");
        }

        boolean save = false;

        //密码加密
        wqunAccount.setPass(SecUtils.passBcrypt(wqunAccount.getPass()));
        save = wqunAdminService.save(wqunAccount);
        if(save){
            return R.ok().message("注册成功");
        }else{
            return R.error().message("注册失败，请联系管理员wt");
        }
    }


}
